package fun.ticsmyc.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import fun.ticsmyc.common.pojo.PageResult;
import fun.ticsmyc.common.utils.IdWorker;
import fun.ticsmyc.item.config.GoodsStatus;
import fun.ticsmyc.item.mapper.OrderMapper;
import fun.ticsmyc.item.pojo.Goods;
import fun.ticsmyc.item.pojo.Order;
import fun.ticsmyc.item.pojo.User;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ticsmyc
 * @date 2020-05-14 13:37
 */
@Service
public class OrderService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private UserService userService;

    /**
     * 预定商品， 【生成订单】
     * @param userId
     * @param goodsId
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean createOrder(Long userId, Long goodsId) {
        Goods goods = this.goodsService.queryItemById(goodsId);
        if(goods.getStatus() !=1 ){
            //商品不是在售状态
            return false;
        }
        User buyer  = this.userService.queryUserByid(userId);
        User saler =  this.userService.queryUserByid(goods.getUserid());


        Order order = new Order();
        // 生成orderId
        long orderId = idWorker.nextId();

        order.setOrderId(orderId);
        order.setCreateTime(new Date());
        order.setGoodsBuyerId(userId);
        order.setGoodsId(goodsId);
        order.setOrder_status(GoodsStatus.BOOK.value());
        this.orderMapper.insert(order);

        //更新商品表中的商品状态
        this.goodsService.updateGoodsStatus(goodsId, GoodsStatus.BOOK.value());


        //给产品发布者发邮件提醒

        Map<String,String> msg =  new HashMap<>();
        msg.put("email",saler.getEmail());
        msg.put("userName",saler.getUsername());
        msg.put("goodsName",goods.getTitle());
        msg.put("buyerName",buyer.getUsername());
        msg.put("buyerPhone",buyer.getPhone());


        this.amqpTemplate.convertAndSend("XDMALL.SMS.EXCHANGE","sms.order",msg);
        return true;
    }

    /**
     * 查询我的订单 （我预定的商品）
     * @param userId
     * @return
     */
    public PageResult<List<Order>> selectOrdersByUserId(Long userId, Integer page , Integer rows,Integer status) {
        PageHelper.startPage(page,rows);
        Order record = new Order();
        record.setGoodsBuyerId(userId);
        record.setOrder_status(status);
        List<Order> orders = this.orderMapper.select(record);
        PageInfo pageInfo = new PageInfo(orders);
        return new PageResult<>(pageInfo.getList(),pageInfo.getPages(),pageInfo.getTotal());
    }

    /**
     * 完成订单 【确认收货】
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public void finishOrder(Long orderId) {
        Order order = this.orderMapper.selectByPrimaryKey(orderId);
        //修改订单状态为 已完成
        order.setOrder_status(GoodsStatus.FINISH.value());
        this.orderMapper.updateByPrimaryKey(order);
        //修改商品状态为 已售出
        this.goodsService.updateGoodsStatus(order.getGoodsId(),GoodsStatus.FINISH.value());
    }

    /**
     * 取消订单 【终止交易】
     * @param orderId
     */
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long orderId) {
        Order order = this.orderMapper.selectByPrimaryKey(orderId);
        //删除订单表中的记录
        this.orderMapper.deleteByPrimaryKey(orderId);
        //修改商品状态为 在架上
        this.goodsService.updateGoodsStatus(order.getGoodsId(),GoodsStatus.ON_SALE.value());
    }

    /**
     * 删除订单记录【发生在交易成功之后】
     * @param orderId
     */
    public void deleteOrder(Long orderId) {
        this.orderMapper.deleteByPrimaryKey(orderId);
    }


    /**
     * 根据商品id查询订单
     * @param goodsId
     * @return
     */
    public Order selectOrderByGoodsId(Long goodsId) {
        Order record =new Order();
        record.setGoodsId(goodsId);
        return this.orderMapper.selectOne(record);
    }


}
